package com.tl.khadmin.service.impl;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.tl.khadmin.bean.Staff;
import com.tl.khadmin.bean.Staffoperation;
import com.tl.khadmin.bean.Staffrole;
import com.tl.khadmin.bean.Staffroleoperation;
import com.tl.khadmin.bean.Supplier;
import com.tl.khadmin.mapper.StaffMapper;
import com.tl.khadmin.mapper.StaffoperationMapper;
import com.tl.khadmin.mapper.StaffroleMapper;
import com.tl.khadmin.mapper.StaffroleoperationMapper;
import com.tl.khadmin.mapper.SupplierMapper;
import com.tl.khadmin.service.RegistIService;
import com.tl.khadmin.util.CommonUtil;

@Service
public class RegistServiceImpl implements RegistIService{

	@Resource
	private SupplierMapper supplierMapper;
	@Resource
	private StaffroleMapper staffroleMapper;
	@Resource
	private StaffMapper staffMapper;
	@Resource
	private StaffoperationMapper staffoperationMapper;
	@Resource
	private StaffroleoperationMapper staffroleoperationMapper;
	
	@Override
	public String regist(Supplier supplier) {
		if(supplierMapper.count(supplier.getContactPhone(), null) > 0) {
			return CommonUtil.returnMapResultToJson("fail", "该手机号已注册");
		}
		if(supplierMapper.count(null, supplier.getSupplierName()) > 0) {
			return CommonUtil.returnMapResultToJson("fail", "供应商名称已存在");
		}
		
		int result = supplierMapper.insertSelective(supplier);
		if(result == 1){ 
			generateData(supplier);
		}
		return CommonUtil.returnMapResultToJson("success", "注册成功，审核中");
	}

	/**
	 * 初始化数据，角色、角色权限、管理员账号
	 * @param supplier
	 */
	private void generateData(Supplier supplier) {
		//初始化角色
		int roleValue = this.generateRole(supplier);
		if(roleValue != -1) {
			//初始化角色账号
			int ret = this.generateStaff(roleValue, supplier);
			//初始化角色权限
			int row = this.generatePermissionsForRole(roleValue);
		} 
	}
	
	/**
	 * 初始化供应商管理员角色
	 * @param supplierId
	 * @return  -1初始化失败，否则返回roleId
	 */
	private int generateRole(Supplier supplier) {
		Staffrole staffrole = new Staffrole();
		staffrole.setName("管理员");
		staffrole.setSupplierId(supplier.getId());
		staffrole.setValue(1);
		staffrole.setDescription("初始化管理员");
		int row = staffroleMapper.insertSelective(staffrole);
		staffroleMapper.updateValue(staffrole.getId());
		if(row == 1){
			return staffrole.getId();
		} 
		return -1;
	}
	
	/**
	 * 
	 * @param staffroleId
	 * @param supplier
	 * @return -1初始化失败，否则返回staffId
	 */
	private int generateStaff(Integer staffroleId, Supplier supplier) {
		Staff staff = new Staff();
		staff.setCreatetime(new Date());
		staff.setLoginname(supplier.getContactPhone());
		staff.setNickname(supplier.getContactName());
		staff.setPassword(CommonUtil.sign("666666","UTF-8").toLowerCase());
		staff.setPhone(supplier.getContactPhone());
		staff.setRole(staffroleId);
		staff.setStatus(1);
		staff.setSupplierId(supplier.getId());
		int row = staffMapper.insertSelective(staff); 
		if(row != 1) {
			return -1;
		}
		return 1;
	}
	
	/**
	 * 初始化角色权限
	 * @param staffroleId
	 * @return  -1初始化失败，否则成功
	 */
	private int generatePermissionsForRole(Integer staffroleId) {
		Map<String, Object> param = new HashMap<>();
		param.put("isopen", 0);
		List<Staffoperation> list = staffoperationMapper.getStaffoperationlist(param);
		if(list!=null && list.size()>0) {
			List<Staffroleoperation> addRoleOptlist = new ArrayList<Staffroleoperation>(); 
			for(Staffoperation oper : list) {
				Staffroleoperation temp = new Staffroleoperation(); 
				temp.setModuleid(oper.getId());
				temp.setOptvalue(oper.getParentid());
				temp.setRolevalue(staffroleId);  
				addRoleOptlist.add(temp);
			}
			int ret = staffroleoperationMapper.batchAdd(addRoleOptlist);
			if(ret > 0) {
				return 1;
			}else{
				return -1;
			}
		} 
		return 1;
	}
	
	@Override
	public Map<String, String> upLoadImg(String basePath, MultipartFile file) {
		Map<String, String> ret = new HashMap<String, String>();
		if (file == null){
			ret.put("result", "fail");
			return ret;
		}
		try {
			DateFormat df = new SimpleDateFormat("yyyyMMddhhmmssSSS");
			File imgDir = new File(basePath);
			if (!imgDir.exists()){
				imgDir.mkdirs(); 
			}
			String datePath = df.format(new Date());
			String picurl = datePath + ".jpg";
			File toFile = new File(basePath, picurl);
			file.transferTo(toFile); 
			ret.put("result", "success");
			ret.put("message", "/upload/productimg/" + picurl);
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			ret.put("reulst", "fail");
			return ret;
		} 
	}
	
	
}
